<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>店铺签到弹窗</title>
    <style>
        :root {
            --theme-color-r: 226;
            --theme-color-g: 65;
            --theme-color-b: 71;
            --theme-color: rgb(var(--theme-color-r), var(--theme-color-g), var(--theme-color-b));
            --theme-color-dark: rgb(180, 50, 55); /* Darker shade for gradient or accents */
            --text-color: #333;
            /* --background-color: #f0f2f5; */
            --popup-background: #fff;
            --border-radius-large: 20px;
            --border-radius-medium: 12px;
            --box-shadow: 0 12px 35px rgba(0, 0, 0, 0.12);
            --success-color: #28a745;
            --success-color-light-fill: rgba(40, 167, 69, 0.1); /* Light fill for checkmark background */
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
            background-color: transparent;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            overflow: hidden;
        }

        #checkInTriggerButton {
            padding: 15px 30px;
            font-size: 18px;
            font-weight: 500;
            color: white;
            background-image: linear-gradient(45deg, var(--theme-color), var(--theme-color-dark));
            border: none;
            border-radius: var(--border-radius-medium);
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(var(--theme-color-r), var(--theme-color-g), var(--theme-color-b), 0.4);
        }

        #checkInTriggerButton:hover {
            transform: translateY(-3px) scale(1.05);
            box-shadow: 0 8px 20px rgba(var(--theme-color-r), var(--theme-color-g), var(--theme-color-b), 0.5);
        }

        #checkInTriggerButton:active {
            transform: translateY(-1px) scale(1);
            box-shadow: 0 4px 10px rgba(var(--theme-color-r), var(--theme-color-g), var(--theme-color-b), 0.3);
        }

        .popup-container {
            position: fixed;
            /* top: 0;
            left: 0; */
            width: 80%;
            height: 100%;
            /* background-color: rgba(0, 0, 0, 0.65); */
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            visibility: hidden;
            /* Transition for the container fade-in */
            transition: opacity 0.3s ease, visibility 0.3s ease;
            z-index: 1000;
        }

        .popup-container.active {
            opacity: 1;
            visibility: visible;
        }

        .popup-content {
            background-color: var(--popup-background);
            padding: 25px 30px;
            border-radius: var(--border-radius-large);
            box-shadow: var(--box-shadow);
            width: 90%;
            max-width: 380px;
            text-align: center;
            /* Initial state for entrance animation */
            opacity: 0;
            transform: translateY(-25px) scale(0.97);
            /* Transition for the content's entrance */
            transition: opacity 0.35s cubic-bezier(0.25, 0.8, 0.25, 1), transform 0.35s cubic-bezier(0.25, 0.8, 0.25, 1.1);
        }

        .popup-container.active .popup-content {
            opacity: 1;
            transform: translateY(0) scale(1);
        }

        .popup-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 20px; /* Increased margin */
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            position: relative;
        }

        .shop-icon-container {
            width: 55px; /* Adjusted size */
            height: 55px;
            margin-bottom: 12px;
            animation: breathe 2.8s ease-in-out infinite;
        }

        .shop-icon-container svg {
            width: 100%;
            height: 100%;
        }

        @keyframes breathe {
            0%, 100% { transform: scale(1); opacity: 0.95; }
            50% { transform: scale(1.06); opacity: 1; }
        }

        .popup-header h2 {
            margin: 0;
            font-size: 21px;
            color: var(--theme-color);
            font-weight: 600;
        }

        .close-button {
            position: absolute;
            top: -10px; /* Adjusted position */
            right: -10px; /* Adjusted position */
            font-size: 28px;
            color: #999; /* Slightly lighter initial color */
            cursor: pointer;
            transition: color 0.2s ease, transform 0.3s ease;
            background-color: #fff;
            border-radius: 50%;
            width: 32px; /* Slightly larger tap area */
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .close-button:hover {
            color: var(--text-color);
            transform: rotate(180deg) scale(1.1);
        }

        .popup-body {
            margin-bottom: 20px;
        }

        .status-message {
            font-size: 17px;
            color: var(--text-color);
            margin-bottom: 18px;
            font-weight: 500;
            min-height: 22px;
        }

        .progress-bar-container {
            width: 100%;
            background-color: #e9ecef;
            border-radius: 25px;
            margin-bottom: 18px;
            overflow: hidden;
            box-shadow: inset 0 1px 2px rgba(0,0,0,0.075);
        }

        .progress-bar {
            width: 0%;
            height: 18px;
            background: linear-gradient(90deg, var(--theme-color-dark), var(--theme-color));
            border-radius: 25px;
            transition: width 0.15s linear;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 10px;
            font-weight: bold;
        }

        .loading-details {
            margin-top: 10px;
            font-size: 12px;
            color: #6c757d; /* Bootstrap muted color */
            max-height: 60px;
            overflow-y: hidden;
            text-align: left;
            padding-left: 10px;
            line-height: 1.5;
        }

        .loading-details div {
            opacity: 0;
            animation: quickFadeIn 0.2s ease forwards;
            margin-bottom: 3px;
        }

        @keyframes quickFadeIn {
            from { opacity: 0; transform: translateY(5px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .popup-footer {
            text-align: center;
        }

        .success-message {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: var(--success-color);
            font-weight: bold;
            opacity: 0;
            transform: translateY(15px) scale(0.9); /* Initial state for entrance */
        }
        .success-message.visible {
            opacity: 1;
            transform: translateY(0) scale(1);
            transition: opacity 0.4s ease 0.1s, transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0.1s;
        }

        /* SVG Checkmark Animation */
        .checkmark {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: block;
            stroke-width: 3; /* Made slightly thicker for visibility */
            stroke: var(--success-color); /* Stroke color defined here */
            stroke-miterlimit: 10;
            margin-right: 12px;
            /* The fill animation is now on the circle itself, not a box-shadow */
        }

        .checkmark-circle {
            stroke-dasharray: 166;
            stroke-dashoffset: 166;
            stroke-width: inherit; /* Inherit from .checkmark */
            stroke: var(--success-color); /* Explicitly set stroke */
            fill: none; /* Crucial: No fill initially */
            animation: success-stroke-circle 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards,
                       success-fill-circle 0.4s ease-in-out 0.5s forwards; /* Fill starts after stroke a bit */
        }

        .checkmark-check {
            transform-origin: 50% 50%;
            stroke-dasharray: 48;
            stroke-dashoffset: 48;
            stroke-width: inherit; /* Inherit from .checkmark */
            stroke: var(--success-color); /* Explicitly set stroke */
            fill: none; /* No fill for the check path */
            animation: success-stroke-check 0.35s cubic-bezier(0.65, 0, 0.45, 1) 0.7s forwards; /* Delayed to start after circle is mostly drawn */
        }

        @keyframes success-stroke-circle {
            100% { stroke-dashoffset: 0; }
        }
        @keyframes success-fill-circle {
            100% { fill: var(--success-color-light-fill); } /* Light fill for the circle background */
        }
        @keyframes success-stroke-check {
            100% { stroke-dashoffset: 0; }
        }

        /* Optional: scale effect for the whole checkmark SVG after animations */
        .success-message.visible .checkmark {
             animation: success-scale-svg .3s ease-in-out 1s both; /* Starts after other animations */
        }

        @keyframes success-scale-svg {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        /* 添加胶囊按钮样式 */
        .capsule-button {
            display: none; /* 默认隐藏 */
            width: 85%;
            margin: 20px auto 5px;
            padding: 12px 0;
            font-size: 16px;
            font-weight: 500;
            color: white;
            background-image: linear-gradient(45deg, var(--theme-color), var(--theme-color-dark));
            border: none;
            border-radius: 50px; /* 胶囊形状 */
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(var(--theme-color-r), var(--theme-color-g), var(--theme-color-b), 0.3);
            transform: translateY(20px);
            opacity: 0;
        }

        .capsule-button.visible {
            display: block;
            animation: slide-up-fade-in 0.5s ease forwards 0.8s; /* 延迟显示，在"签到成功"动画之后 */
        }

        @keyframes slide-up-fade-in {
            0% {
                transform: translateY(20px);
                opacity: 0;
            }
            100% {
                transform: translateY(0);
                opacity: 1;
            }
        }

        /* 增加弹窗内容底部的内边距，为按钮留出空间 */
        .popup-content {
            padding-bottom: 15px;
        }

        /* 优化成功信息样式，使其与按钮更匹配 */
        .success-message {
            margin-bottom: 0;
            padding-bottom: 5px;
        }

        /* 添加错误信息样式 */
        .error-message {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: #dc3545;
            font-weight: bold;
            opacity: 0;
            transform: translateY(15px) scale(0.9);
        }

        .error-message.visible {
            opacity: 1;
            transform: translateY(0) scale(1);
            transition: opacity 0.4s ease 0.1s, transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) 0.1s;
        }
    </style>
</head>
<body>

<!-- <button id="checkInTriggerButton">探店签到</button> -->

<div id="checkInPopup" class="popup-container">
    <div class="popup-content">
        <div class="popup-header">
            <div class="shop-icon-container">
                <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
                    <defs>
                        <linearGradient id="awningGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                            <stop offset="0%" style="stop-color:var(--theme-color); stop-opacity:1" />
                            <stop offset="100%" style="stop-color:var(--theme-color-dark); stop-opacity:1" />
                        </linearGradient>
                    </defs>
                    <rect x="12" y="32" width="76" height="58" rx="6" ry="6" style="fill:#f0f0f0;" /> <path d="M8 38 L92 38 L88 25 L12 25 Z" style="fill:url(#awningGradient);" /> <rect x="38" y="50" width="24" height="40" rx="4" ry="4" style="fill:#d0d0d0;" /> <circle cx="42" cy="70" r="2" style="fill:#888888;" /> <rect x="15" y="8" width="70" height="12" rx="3" ry="3" style="fill:var(--theme-color-dark);" />
                    <text x="50" y="18" font-family="Arial, Helvetica, sans-serif" font-size="9" fill="white" text-anchor="middle" font-weight="bold">店铺签到</text>
                </svg>
            </div>
            <h2>签到状态</h2>
            <!-- 移除原有的关闭按钮 -->
        </div>
        <div class="popup-body">
            <div id="statusMessage" class="status-message">准备签到...</div>
            <div class="progress-bar-container">
                <div id="progressBar" class="progress-bar">0%</div>
            </div>
            <div id="loadingDetails" class="loading-details">
            </div>
        </div>
        <div class="popup-footer">
            <div id="successMessage" class="success-message" style="display: none;">
                <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                    <circle class="checkmark-circle" cx="26" cy="26" r="25"/>
                    <path class="checkmark-check" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
                </svg>
                <span id="successText">签到成功！</span>
            </div>
            <div id="errorMessage" class="error-message" style="display: none;">
                <span id="errorText">签到失败</span>
            </div>
            <!-- 新增底部胶囊按钮 -->
            <button id="closeButton" class="capsule-button" onclick="closePopup()">知道了</button>
        </div>
    </div>
</div>
<script>
    const backendBaseUrl = 'http://visionsic.com:1120'; // 后端服务地址
    const checkInButton = document.getElementById('checkInTriggerButton');
    const popup = document.getElementById('checkInPopup');
    const statusMessage = document.getElementById('statusMessage');
    const progressBar = document.getElementById('progressBar');
    const loadingDetailsContainer = document.getElementById('loadingDetails');
    const successMessageContainer = document.getElementById('successMessage');
    const errorMessageContainer = document.getElementById('errorMessage');
    const closeBtn = document.querySelector('.close-button');
    const closeButton = document.getElementById('closeButton');
    const successText = document.getElementById('successText');
    const errorText = document.getElementById('errorText');

    const calculationSteps = [
        "初始化签到模块...",
        "检测网络环境...",
        "正在获取店铺位置...",
        "匹配店铺信息...",
        "安全扫描...",
        "验证用户资格...",
        "检查活动有效性...",
        "生成签到令牌...",
        "记录签到数据...",
        "同步至云端...",
        "即将完成..."
    ];

    let currentStep = 0;
    let checkInData = null; // 存储签到数据
    const STEP_DURATION = 180; // milliseconds per step (adjust for speed)

    // 页面加载完成后自动打开签到弹窗
    document.addEventListener('DOMContentLoaded', function() {
        // 延迟一小段时间后打开弹窗，以确保页面完全渲染
        setTimeout(function() {
            // 调用全局签到弹窗方法
            window.openCheckInPopup();
        }, 50); // 500毫秒延迟，可根据需要调整
    });

    function openPopup() {
        popup.classList.add('active');
        resetPopup();
        startCheckInProcess();
    }

    function closePopup() {
        // 在关闭弹窗前通知Android结果
        try {
            if (typeof AndroidOther !== 'undefined' && AndroidOther.onClickInSuccess) {
                // 根据结果传递不同的状态值
                if (window.checkInResult === 'success') {
                    AndroidOther.onClickInSuccess(1); // 成功
                    console.log("已通知Android签到成功");
                } else {
                    AndroidOther.onClickInSuccess(0); // 失败
                    console.log("已通知Android签到失败");
                }
            }
        } catch (error) {
            console.error("调用Android回调函数失败:", error);
        }

        // 关闭弹窗
        popup.classList.remove('active');

        // Reset after animation, consistent with CSS transition for .popup-content
        setTimeout(() => {
            resetPopup();
        }, 350);
    }

    function resetPopup() {
        currentStep = 0;
        statusMessage.textContent = "准备签到...";
        statusMessage.style.display = 'block';

        progressBar.style.width = '0%';
        progressBar.textContent = '0%';
        progressBar.parentElement.style.display = 'block';

        loadingDetailsContainer.innerHTML = '';
        loadingDetailsContainer.style.display = 'block';

        successMessageContainer.style.display = 'none';
        successMessageContainer.classList.remove('visible');

        errorMessageContainer.style.display = 'none';
        errorMessageContainer.classList.remove('visible');

        // 隐藏关闭按钮
        closeButton.classList.remove('visible');

        // Clear any dynamically added animations if necessary, e.g., if old intervals are running
        if (window.progressTimeout) clearTimeout(window.progressTimeout);
    }

    async function startCheckInProcess() {
        try {
            // 开始进度条动画到中间位置
            startInitialProgress();

            // 尝试从Android获取签到数据，最多尝试3次
            let androidDataSuccess = false;
            let tryCount = 0;
            const maxTryCount = 3;

            while (!androidDataSuccess && tryCount < maxTryCount) {
                tryCount++;
                try {
                    // 添加正在尝试的提示
                    statusMessage.textContent = `正在获取签到数据(${tryCount}/${maxTryCount})...`;

                    // 尝试从Android获取数据
                    // 首先从Android获取签到数据
                    if (typeof AndroidOther !== 'undefined' && AndroidOther.han) {
                        // 从Android调用获取数据
                        const androidData = AndroidOther.han();
                        console.warn("hahahahahahah")
                        console.warn(androidData)
                        console.warn("---------------------------------------")

                        if (androidData) {
                            try {
                                checkInData = JSON.parse(androidData);
                                console.warn(checkInData)
                                // 检查并修正数据格式
                                if (Array.isArray(checkInData)) {
                                    console.log("警告：Android返回了数组格式的数据，正在尝试修正");
                                    if (checkInData.length > 0) {
                                        checkInData = checkInData[0]; // 使用数组中的第一个对象
                                    } else {
                                        throw new Error("Android返回的数据数组为空");
                                    }
                                }

                                androidDataSuccess = true;
                                // 获取成功，继续进度条
                                // continueProgressAfterAndroid();
                                break;
                            } catch (error) {
                                console.error("解析Android数据失败:", error);
                            }
                        }
                    }

                    // 如果尝试次数未达到最大值，等待一秒后重试
                    if (tryCount < maxTryCount) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                } catch (error) {
                    console.error(`第${tryCount}次尝试获取数据失败:`, error);
                    // 如果是最后一次尝试，不再等待
                    if (tryCount < maxTryCount) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }
            }

            // 检查是否成功获取数据
            if (!androidDataSuccess) {
                // 多次尝试后仍未获取数据，显示错误
                cancelProgress();
                showError("无法获取签到数据，请确保App权限正常");
                return;
            }
        } catch (error) {
            console.error("处理签到过程出错:", error);
            cancelProgress();
            showError("获取签到数据失败");
            return;
        }
    }
    // 初始化进度条到60%位置
    function startInitialProgress() {
        statusMessage.textContent = "正在签到...";
        loadingDetailsContainer.innerHTML = ''; // 清空之前的详情

        const midpointIndex = Math.floor(calculationSteps.length / 2) - 1;
        let progress = 0;
        let accumulatedDelay = 50; // 初始延迟

        // 前半部分的动画，但最大只到60%
        for (let i = 0; i <= midpointIndex; i++) {
            const stepText = calculationSteps[i];
            window.progressTimeout = setTimeout(() => {
                if (!popup.classList.contains('active')) return;

                // 进度计算改为0-60%范围
                progress = Math.round((i / midpointIndex) * 60);
                // 确保不超过60%
                progress = Math.min(progress, 60);
                
                progressBar.style.width = progress + '%';
                progressBar.textContent = progress + '%';

                const detailElement = document.createElement('div');
                detailElement.textContent = stepText;
                loadingDetailsContainer.appendChild(detailElement);

                // 自动滚动
                if (loadingDetailsContainer.scrollHeight > loadingDetailsContainer.clientHeight) {
                    loadingDetailsContainer.scrollTop = loadingDetailsContainer.scrollHeight;
                }
            }, accumulatedDelay);

            accumulatedDelay += STEP_DURATION * (0.6 + Math.random() * 0.4);
        }
    }

    // 在获取Android数据成功后继续进度条
    function continueProgressAfterAndroid() {
        // 确保进度条已经到达60%
        progressBar.style.width = '60%';
        progressBar.textContent = '60%';
        
        const midpointIndex = Math.floor(calculationSteps.length / 2) - 1;
        let accumulatedDelay = 50; // 初始延迟

        // 后半部分的动画，从60%到100%
        for (let i = midpointIndex + 1; i < calculationSteps.length; i++) {
            const stepText = calculationSteps[i];
            window.progressTimeout = setTimeout(() => {
                if (!popup.classList.contains('active')) return;

                // 进度计算改为60-100%范围
                const stepProgress = (i - midpointIndex - 1) / (calculationSteps.length - midpointIndex - 1);
                const progress = Math.round(60 + stepProgress * 40);
                
                progressBar.style.width = progress + '%';
                progressBar.textContent = progress + '%';

                const detailElement = document.createElement('div');
                detailElement.textContent = stepText;
                loadingDetailsContainer.appendChild(detailElement);

                // 自动滚动
                if (loadingDetailsContainer.scrollHeight > loadingDetailsContainer.clientHeight) {
                    loadingDetailsContainer.scrollTop = loadingDetailsContainer.scrollHeight;
                }

                // 进度条完成后调用API
                if (i >= calculationSteps.length - 1) {
                    progressBar.style.width = '100%';
                    progressBar.textContent = '100%';
                    statusMessage.textContent = "处理完毕!";

                    // 调用实际的签到API
                    setTimeout(async () => {
                        try {
                            await performCheckIn();
                        } catch (error) {
                            console.error("签到失败:", error);
                            showError("签到请求失败，请稍后重试");
                        }
                    }, 250);
                }
            }, accumulatedDelay);

            accumulatedDelay += STEP_DURATION * (0.6 + Math.random() * 0.4);
        }
    }

    // 取消进度条动画
    function cancelProgress() {
        // 清除所有超时
        if (window.progressTimeout) {
            clearTimeout(window.progressTimeout);
        }
    }

    // 执行实际的签到API调用
    async function performCheckIn() {
        try {
            if (!checkInData) {
                throw new Error("没有签到数据");
            }

            const response = await fetch(`${backendBaseUrl}/shop/check-in/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(checkInData)
            });

            const result = await response.json();

            if (result.status === "success") {
                // 更新成功消息文本
                if (result.action === "done") {
                    successText.textContent = "签到成功！";
                } else if (result.action === "undone") {
                    successText.textContent = "取消签到成功！";
                }
                showSuccess();
            } else {
                showError(result.message || "签到失败，请稍后重试");
            }
        } catch (error) {
            console.error("API调用失败:", error);
            showError("网络请求失败，请检查网络连接");
        }
    }

    function showSuccess() {
        if (!popup.classList.contains('active')) return;

        statusMessage.style.display = 'none';
        loadingDetailsContainer.style.display = 'none';
        progressBar.parentElement.style.display = 'none';

        successMessageContainer.style.display = 'flex';
        void successMessageContainer.offsetWidth; // Force reflow
        successMessageContainer.classList.add('visible');

        // 显示关闭按钮
        closeButton.classList.add('visible');

        // 标记当前状态为成功
        window.checkInResult = 'success';
    }

    function showError(message) {
        if (!popup.classList.contains('active')) return;

        statusMessage.style.display = 'none';
        loadingDetailsContainer.style.display = 'none';
        progressBar.parentElement.style.display = 'none';

        // 设置错误消息
        errorText.textContent = message || "签到失败，请稍后重试";
        errorMessageContainer.style.display = 'flex';
        void errorMessageContainer.offsetWidth; // Force reflow
        errorMessageContainer.classList.add('visible');

        // 显示关闭按钮
        closeButton.classList.add('visible');

        // 标记当前状态为失败
        window.checkInResult = 'error';
    }

    // 全局签到弹窗方法 - 现在会自动调用，但也可以从其他地方手动调用
    window.openCheckInPopup = function() {
        if (!popup) return; // 安全检查
        popup.classList.add('active');
        resetPopup();
        startCheckInProcess();
    };

    // 全局关闭弹窗方法
    window.closeCheckInPopup = function() {
        if (!popup) return; // 安全检查
        popup.classList.remove('active');
        // 动画结束后重置
        setTimeout(() => {
            resetPopup();
        }, 350);
    };

    //checkInButton.addEventListener('click', openPopup);
    if (closeBtn) closeBtn.addEventListener('click', closePopup);

    popup.addEventListener('click', (event) => {
        if (event.target === popup) {
            closePopup();
        }
    });
</script>
</body>
</html>